package com.gusha.controller;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.gusha.config.SysOperateLog;
import com.gusha.utils.Constants;
import com.gusha.utils.FileUtils;
import com.gusha.utils.JsonResult;
import com.gusha.utils.Md5Util;
import com.gusha.utils.UpdateUtil;
import com.gusha.utils.WebValueUtil;

import com.gusha.service.UserService;
import com.gusha.dao.ConfigAgentDao;
import com.gusha.dao.SysAreaDao;
import com.gusha.dao.UserDao;
import com.gusha.model.ConfigAgent;
import com.gusha.model.SysArea;
import com.gusha.model.User;


/**
 * @Created：2018-11-06 14:11:32
 * @Author LightSound的代码生成器
 * @Description:UserController控制类
 */
@Controller
@RequestMapping("/gx/user")
public class UserController {

    // 注入Dao
    @Autowired
    private UserDao userDao;
    @Autowired
    private SysAreaDao sysAreaDao;
    @Autowired
    private ConfigAgentDao configAgentDao;
    
    // 注入Service
    @Autowired
    private UserService userService;

    // 查询列表
    @RequestMapping("list")
    @SysOperateLog(operate = "查看用户列表")
    public String list(Model model, HttpServletRequest request) {

        //请求参数
        String pageIndex = WebValueUtil.getWebValue(request, "pageIndex");
        String userType = WebValueUtil.getWebValue(request, "userType");
        String userNo = WebValueUtil.getWebValue(request, "userNo");
        String userName = WebValueUtil.getWebValue(request, "userName");
        String realName = WebValueUtil.getWebValue(request, "realName");
        String phone = WebValueUtil.getWebValue(request, "phone");
        String cardNo = WebValueUtil.getWebValue(request, "cardNo");
        String areaProvince = WebValueUtil.getWebValue(request, "areaProvince");
        String areaCity = WebValueUtil.getWebValue(request, "areaCity");
        String areaDistrict = WebValueUtil.getWebValue(request, "areaDistrict");

        //参数封装
        int pageNo = 0;
        //判断pageindex不为空并且大于0
        if (StringUtils.isNotBlank(pageIndex)) {
            pageNo = Integer.parseInt(pageIndex);
        }
        User user = new User();
        if (StringUtils.isNotBlank(userType)) {
        	user.setUserType(Integer.parseInt(userType));
        }
        if (StringUtils.isNotBlank(userNo)) {
        	user.setUserNo(userNo);
        }
        if (StringUtils.isNotBlank(userName)) {
        	user.setUserName(userName);
        }
        if (StringUtils.isNotBlank(realName)) {
        	user.setRealName(realName);
        }
        if (StringUtils.isNotBlank(phone)) {
        	user.setPhone(phone);
        }
        if (StringUtils.isNotBlank(cardNo)) {
        	user.setCardNo(cardNo);
        }
        List<SysArea> listProvince = sysAreaDao.findAllByPCode("00");
        List<SysArea> listCity = new ArrayList<SysArea>();
        List<SysArea> listDistrict = new ArrayList<SysArea>();
        if (StringUtils.isNotBlank(areaProvince)) {
        	SysArea province = sysAreaDao.findByCode(areaProvince);
        	user.setAreaProvince(province);
        	listCity = sysAreaDao.findAllByPCode(areaProvince);
        }
        if (StringUtils.isNotBlank(areaCity)) {
        	SysArea city = sysAreaDao.findByCode(areaCity);
        	user.setAreaCity(city);
        	listDistrict = sysAreaDao.findAllByPCode(areaCity);
        }
        if (StringUtils.isNotBlank(areaDistrict)) {
        	SysArea district = sysAreaDao.findByCode(areaDistrict);
        	user.setAreaDistrict(district);
        }

        //获取分页数据
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(pageNo, Constants.DEFAULT_PAGESIZE, sort);
        Page<User> page = userService.findAll(pageable, user);
        
        model.addAttribute("page", page);
        model.addAttribute("listProvince", listProvince);
        model.addAttribute("listCity", listCity);
        model.addAttribute("listDistrict", listDistrict);
        model.addAttribute("userType", userType);
        model.addAttribute("userNo", userNo);
        model.addAttribute("userName", userName);
        model.addAttribute("realName", realName);
        model.addAttribute("phone", phone);
        model.addAttribute("cardNo", cardNo);
        model.addAttribute("areaProvince", areaProvince);
        model.addAttribute("areaCity", areaCity);
        model.addAttribute("areaDistrict", areaDistrict);
        return "/admin/user/list";
    }

    // 进入添加页面
    @RequestMapping("toAdd")
    @SysOperateLog(operate = "进入用户添加页面")
    public String toAdd(Model model, HttpServletRequest request) {
    	String userType = WebValueUtil.getWebValue(request, "userType");
    	model.addAttribute("userType", userType);
    	List<SysArea> listProvince = sysAreaDao.findAllByPCode("00");
    	model.addAttribute("listProvince", listProvince);
    	List<SysArea> listCity = new ArrayList<SysArea>();
        List<SysArea> listDistrict = new ArrayList<SysArea>();
        model.addAttribute("listCity", listCity);
        model.addAttribute("listDistrict", listDistrict);
        
        List<ConfigAgent> listAgentLevel = configAgentDao.findAllByIsDelete(Constants.RECOVERY);
        model.addAttribute("listAgentLevel", listAgentLevel);
        
        List<User> listDLS = new ArrayList<User>();
        List<User> listYWY = new ArrayList<User>();
        String type = "";
        if("1".equals(userType)) {
        	type = "NH";
        	listYWY = userDao.findAllByUserTypeOrUserType(Constants.USER_YWY,Constants.USER_YYBYWY);
        }
        if("2".equals(userType)) {
        	type = "DLS";
        }
        if("3".equals(userType)) {
        	type = "YWY";
        }
        if("4".equals(userType)) {
        	type = "YYB";
        	listDLS = userDao.findAllByUserType(Constants.USER_DLS);
        }
        if("5".equals(userType)) {
        	type = "DLSYWY";
        	listDLS = userDao.findAllByUserType(Constants.USER_DLS);
        }
        model.addAttribute("listDLS", listDLS);
        model.addAttribute("listYWY", listYWY);
        model.addAttribute("userNo", Constants.getUserNo(type));
        return "/admin/user/form";
    }

    // 进入编辑页面
    @RequestMapping("toEdit")
    @SysOperateLog(operate = "进入用户编辑页面")
    public String toEdit(Model model, HttpServletRequest request) {

        //请求参数
        String id = WebValueUtil.getWebValue(request, "id");
        String userType = WebValueUtil.getWebValue(request, "userType");
    	model.addAttribute("userType", userType);

    	List<SysArea> listCity = new ArrayList<SysArea>();
        List<SysArea> listDistrict = new ArrayList<SysArea>();
        List<User> listDLS = new ArrayList<User>();
        List<User> listYYB = new ArrayList<User>();
        List<User> listYWY = new ArrayList<User>();
        if (StringUtils.isNotBlank(id)) {
            if(userDao.existsById(new BigInteger(id))) {
                User user = userDao.getOne(new BigInteger(id));
                model.addAttribute("obj", user);
                model.addAttribute("userNo", user.getUserNo());
                listCity = sysAreaDao.findAllByPCode(user.getAreaProvince().getCode());
                listDistrict = sysAreaDao.findAllByPCode(user.getAreaCity().getCode());
                
                if("1".equals(userType)) {
                	listYWY = userDao.findAllByUserTypeOrUserType(Constants.USER_YWY,Constants.USER_YYBYWY);
                }
                if("2".equals(userType)) {
                }
                if("3".equals(userType)) {
                }
                if("4".equals(userType)) {
                	listDLS = userDao.findAllByUserType(Constants.USER_DLS);
                }
                if("5".equals(userType)) {
                	User belongYYB = userDao.getOne(user.getBelongId());
                    listYYB = userDao.findAllByUserTypeAndBelongId(Constants.USER_YYB, belongYYB.getBelongId());
                	listDLS = userDao.findAllByUserType(Constants.USER_DLS);
                }
            }
        }        
        List<SysArea> listProvince = sysAreaDao.findAllByPCode("00");
    	model.addAttribute("listProvince", listProvince);
    	model.addAttribute("listCity", listCity);
        model.addAttribute("listDistrict", listDistrict);
        List<ConfigAgent> listAgentLevel = configAgentDao.findAllByIsDelete(Constants.RECOVERY);
        model.addAttribute("listAgentLevel", listAgentLevel);
        model.addAttribute("listDLS", listDLS);
        model.addAttribute("listYYB", listYYB);
        model.addAttribute("listYWY", listYWY);
        return "/admin/user/form";
    }

    // 保存
    @RequestMapping("save")
    @ResponseBody
    @SysOperateLog(operate = "保存用户信息")
    public JsonResult save(User user,HttpServletRequest request) {
        JsonResult result = new JsonResult(false,"保存失败");
        String userType = WebValueUtil.getWebValue(request, "userType");
        //新增判断
        if(user.getId()==null||user.getId().compareTo(new BigInteger("0"))==0) {
        	User userOld = userDao.findByUserName(user.getUserName());
            if(userOld!=null) {
            	if("1".equals(userType)) {
            		result.setMsg("该用户名已存在");
            	}
            	if("2".equals(userType)) {
            		result.setMsg("该用户名已存在");
            	}
            	if("3".equals(userType)) {
            		result.setMsg("该用户名已存在");
            	}
            	if("4".equals(userType)) {
            		result.setMsg("该营业部名称已存在");
            	}
            	if("5".equals(userType)) {
            		result.setMsg("该业务员用户名已存在");
            	}
            	return result;
            }
            userOld = userDao.findByPhone(user.getPhone());
            if(userOld!=null) {
            	result.setMsg("该手机号已存在");
            	return result;
            }
            userOld = userDao.findByCardNo(user.getCardNo());
            if(userOld!=null) {
            	result.setMsg("该身份证号已存在");
            	return result;
            }
            user.setPassword(Md5Util.getMD5Code(user.getPassword()));
            if("1".equals(userType)) {
        		user.setIsChecked(Constants.CHECK_FAI);
        	}
        }else {//更改判断
        	String userNameOld = WebValueUtil.getWebValue(request, "userNameOld");
        	String cardNoOld = WebValueUtil.getWebValue(request, "cardNoOld");
        	String phoneOld = WebValueUtil.getWebValue(request, "phoneOld");
        	if(!userNameOld.equals(user.getUserName())) {
        		User userOld = userDao.findByUserName(user.getUserName());
                if(userOld!=null) {
                	if("1".equals(userType)) {
                		result.setMsg("该用户名已存在");
                	}
                	if("2".equals(userType)) {
                		result.setMsg("该用户名已存在");
                	}
                	if("3".equals(userType)) {
                		result.setMsg("该用户名已存在");
                	}
                	if("4".equals(userType)) {
                		result.setMsg("该营业部名称已存在");
                	}
                	if("5".equals(userType)) {
                		result.setMsg("该业务员用户名已存在");
                	}
                	return result;
                }
        	}
        	if(!phoneOld.equals(user.getPhone())) {
        		User userOld = userDao.findByPhone(user.getPhone());
                 if(userOld!=null) {
                 	result.setMsg("该手机号已存在");
                 	return result;
                 }
        	}
        	if(!cardNoOld.equals(user.getCardNo())) {
        		User userOld = userDao.findByCardNo(user.getCardNo());
                if(userOld!=null) {
                	result.setMsg("该身份证号已存在");
                	return result;
                }
        	}
        }
        String cardIconOld = WebValueUtil.getWebValue(request, "cardIconOld");
        if(!cardIconOld.equals(user.getCardIcon())) {
        	 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
             MultipartFile file = multipartRequest.getFile("file1");
              // 要上传的目标文件存放路径
             String newFileName = FileUtils.getFileName(file.getOriginalFilename());
             String imagePath = Constants.getFilePath("user")+newFileName;
             String localPath = Constants.IMAGE_LOCAL_PATH+Constants.getFilePath("user");
             FileUtils.upload(file, localPath, newFileName);
             user.setCardIcon(imagePath);
        }
        String regIconOld = WebValueUtil.getWebValue(request, "regIconOld");
        if(!regIconOld.equals(user.getRegIcon())) {
        	 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
             MultipartFile file = multipartRequest.getFile("file2");
              // 要上传的目标文件存放路径
             String newFileName = FileUtils.getFileName(file.getOriginalFilename());
             String imagePath = Constants.getFilePath("user")+newFileName;
             String localPath = Constants.IMAGE_LOCAL_PATH+Constants.getFilePath("user");
             FileUtils.upload(file, localPath, newFileName);
             user.setRegIcon(imagePath);
        }
        userDao.saveAndFlush(user);
        result.setFlag(true);
        result.setMsg("保存成功");

        return result;
    }
    
    
    // 进入审核页面
    @RequestMapping("toCheck")
    @SysOperateLog(operate = "进入农户审核页面")
    public String toCheck(Model model, HttpServletRequest request) {

        //请求参数
        String id = WebValueUtil.getWebValue(request, "id");
        String userType = WebValueUtil.getWebValue(request, "userType");
    	model.addAttribute("userType", userType);

    	List<SysArea> listCity = new ArrayList<SysArea>();
        List<SysArea> listDistrict = new ArrayList<SysArea>();
        List<User> listYWY = new ArrayList<User>();
        if (StringUtils.isNotBlank(id)) {
            if(userDao.existsById(new BigInteger(id))) {
                User user = userDao.getOne(new BigInteger(id));
                model.addAttribute("obj", user);
                model.addAttribute("userNo", user.getUserNo());
                listCity = sysAreaDao.findAllByPCode(user.getAreaProvince().getCode());
                listDistrict = sysAreaDao.findAllByPCode(user.getAreaCity().getCode());
                listYWY = userDao.findAllByUserTypeOrUserType(Constants.USER_YWY,Constants.USER_YYBYWY);
            }
        }        
        List<SysArea> listProvince = sysAreaDao.findAllByPCode("00");
    	model.addAttribute("listProvince", listProvince);
    	model.addAttribute("listCity", listCity);
        model.addAttribute("listDistrict", listDistrict);
        model.addAttribute("listYWY", listYWY);
        return "/admin/user/check";
    }
    
    // 审核
    @RequestMapping("doCheck")
    @ResponseBody
    @SysOperateLog(operate = "审核农户")
    public JsonResult doCheck(User user) {
        JsonResult result = new JsonResult(false,"审核失败");
        if (user.getId() != null) {
            User userOld = userDao.getOne(user.getId());
            UpdateUtil.copyNonNullProperties(user, userOld);
        }
        userDao.saveAndFlush(user);
        result.setFlag(true);
        result.setMsg("审核成功");

        return result;
    }


//    // 删除
//    @RequestMapping("delete")
//    @ResponseBody
//    @SysOperateLog(operate = "删除XX信息")
//    public JsonResult delete(BigInteger id) {
//        JsonResult result = new JsonResult(false,"删除失败");
//        if (userDao.existsById(id)) {
//            User user = userDao.getOne(id);
//            user.setIsDelete(Constants.DELETE);
//            userDao.saveAndFlush(user);
//            result.setFlag(true);
//            result.setMsg("删除成功");
//        }else{
//            result.setFlag(false);
//            result.setMsg("该对象信息不存在");
//            return result;
//        }
//        return result;
//    }
//
//
//    // 恢复
//    @RequestMapping("recovery")
//    @ResponseBody
//    @SysOperateLog(operate = "恢复XX信息")
//    public JsonResult recovery(BigInteger id) {
//        JsonResult result = new JsonResult(false,"恢复失败");
//        if (userDao.existsById(id)) {
//            User user = userDao.getOne(id);
//            user.setIsDelete(Constants.RECOVERY);
//            userDao.saveAndFlush(user);
//            result.setFlag(true);
//            result.setMsg("恢复成功");
//        }else{
//            result.setFlag(false);
//            result.setMsg("该对象信息不存在");
//            return result;
//        }
//        return result;
//    }

}
